package directory

import (
	"context"
	"regexp"
	"strings"

	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/utils/pointy"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateDirectoryLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateDirectoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateDirectoryLogic {
	return &UpdateDirectoryLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateDirectoryLogic) UpdateDirectory(req *types.UpdateMediaDirectoryReq) (resp *types.BaseMsgResp, err error) {
	if req.Path != nil && len(strings.TrimSpace(*req.Path)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "file.directoryPathRequired"))
	}

	var path *string
	if req.Path != nil {
		reg := regexp.MustCompile("[^-A-Za-z0-9_.]")
		path = pointy.GetPointer(reg.ReplaceAllString(*req.Path, "_")) // filter out all non word characters
	}

	res, err := l.svcCtx.AttachmentRpc.BackendUpdateFile(l.ctx, &attachmentclient.FileInfo{
		Id:       &req.Id,
		AltText:  req.Title,
		Excerpt:  req.Excerpt,
		Path:     path,
		ParentId: req.ParentId,
	})
	if err != nil {
		return
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
